package com.ag.improvedjava.iterable;

import java.util.Iterator;
import java.util.NoSuchElementException;

final class ConcatIterable<E> implements Iterable<E> {

	private Iterable<E> firstIterable;
	private Iterable<E> secondIterable;
	
	ConcatIterable(Iterable<E> firstIterable, Iterable<E> secondIterable) {
		this.firstIterable = firstIterable;
		this.secondIterable = secondIterable;
	}

	@Override
	public Iterator<E> iterator() {
		return new ConcatIterator<>(firstIterable.iterator(), secondIterable.iterator());
	}
	
}

class ConcatIterator<E> extends UnmodifiableIterator<E> {
	
	private Iterator<E> firstIterator;
	private Iterator<E> secondIterator;

	ConcatIterator(Iterator<E> firstIterator, Iterator<E> secondIterator) {
		this.firstIterator = firstIterator;
		this.secondIterator = secondIterator;
	}

	@Override
	public boolean hasNext() {
		return firstIterator.hasNext() ? true : secondIterator.hasNext();
	}

	@Override
	public E next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		return firstIterator.hasNext() ? firstIterator.next() : secondIterator.next();
	}

}
